/*
 * @Author: lihaogn
 * @Date: 2021-11-13 19:34:43
 * @LastEditTime: 2022-05-27 14:47:14
 * @LastEditor: lihaogn
 * @Description: 用户相关的 vuex
 * @FilePath: \lix-admin-client-vue2\src\store\modules\user.js
 */
import md5 from 'md5'
import { reqLogin } from '@/api/login/api'
import { reqGetUserInfo } from '../../api/user-manage/user/api'
import { lsSetItem, lsGetItem, lsRemoveAllItem } from '@/utils/storage.js'
import { TOKEN, USER_ID } from '@/constant'
import router from '@/router'
import { resetRouter } from '../../router'

export default {
  namespaced: true,
  state: () => ({
    token: lsGetItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    /**
     * @author: lihaogn
     * @Date: 2021-11-18 20:42:29
     * @description: 设置 token
     * @param {*} state - 状态对象
     * @param {*} token - 后端返回的 token 值
     * @return {*}
     */
    setToken(state, token) {
      state.token = token
      // 存储到 localStorage 中
      lsSetItem(TOKEN, token)
    },
    /**
     * @author: lihaogn
     * @Date: 2021-11-18 20:42:32
     * @description:
     * @param {*} state
     * @param {*} userInfo - 用户信息对象
     * @return {*}
     */
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      lsSetItem(USER_ID, userInfo.id)
    }
  },
  actions: {
    /**
     * @author: lihaogn
     * @Date: 2021-11-14 15:58:14
     * @description: 登录
     * @param {*} context
     * @param {*} loginForm - 登录表单信息
     * @return {*}
     */
    async login(context, loginForm) {
      const { username, password } = loginForm

      try {
        const { message, result, success, token } = await reqLogin({
          username,
          password: md5(password)
        })

        if (success) {
          context.commit('setToken', token)
          lsSetItem(USER_ID, result.id)

          return { success: true, message: message }
        } else {
          return { success: false }
        }
      } catch (error) {
        return { success: false }
      }
    },
    /**
     * @author: lihaogn
     * @Date: 2021-11-14 15:58:30
     * @description: 获取用户信息
     * @param {*} context
     * @return {*}
     */
    async getUserInfo(context) {
      let userId = lsGetItem(USER_ID)
      if (typeof userId === 'string') {
        const res = await reqGetUserInfo(userId)
        if (res.success) {
          let result = res.result
          context.commit('setUserInfo', result)

          // 处理用户权限，筛选出需要添加的权限
          const { permission, role } = result
          let filterRoutes
          if (role.some(r => r.id === '001')) {
            // 如果是白名单中的角色，则展示全部的路由
            filterRoutes = await context.dispatch(
              'permission/filterRoutes',
              false,
              { root: true }
            )
          } else {
            filterRoutes = await context.dispatch(
              'permission/filterRoutes',
              permission.pages,
              { root: true }
            )
          }

          filterRoutes.forEach(item => {
            router.addRoute(item)
          })

          return result
        } else {
          context.dispatch('logout')
        }
      } else {
        context.dispatch('logout')
      }
    },
    /**
     * @author: lihaogn
     * @Date: 2021-11-18 20:42:08
     * @description: 退出登录
     * @param {*} context
     * @return {*}
     */
    logout(context) {
      context.commit('setToken', '')
      context.commit('setUserInfo', {})
      context.commit(
        'app/removeTagsView',
        { type: 'all', index: 0 },
        { root: true }
      )
      lsRemoveAllItem()
      router.push('/login')
      // 重置路由
      resetRouter()
    }
  }
}
